<!--
  * 硬件接口管理
-->
<template>
  <!---------- 查询表单form begin ----------->

  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="厂商名称" class="smart-query-form-item">
        <CustomSelect
          style="width: 180px"
          v-model:value="queryForm.manufacturerId"
          :placeholder="'请选择厂商名称'"
          queryParamKey="manufacturerName"
          :api="manufacturerApi.page"
          label-field="manufacturerName,id"
        />
      </a-form-item>
      <a-form-item label="设备类型" class="smart-query-form-item">
        <a-select v-model:value="queryForm.deviceType" style="width: 180px" allowClear :options="DEVICE_TYPE" placeholder="请选择设备类型" />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-title">数据列表</div>
      <div class="smart-table-operate-block">
        <a-button @click="showForm" type="primary" size="small">
          <template #icon>
            <PlusOutlined />
          </template>
          新增
        </a-button>
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :loading="tableLoading" :pagination="false" />
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>
  </a-card>

  <a-modal
    :title="moduleListOptions.title"
    :width="1200"
    :open="moduleListOptions.open"
    :footer="false"
    @cancel="onmoduleListClose"
    :maskClosable="false"
    :destroyOnClose="true"
  >
    <DeviceModuleList :row-data="moduleListOptions.data" class="m-b-4" />
    <DeviceModuleList v-if="moduleListOptions.data.deviceType == '1'" :type="1" :row-data="moduleListOptions.data" />
    <div>
      <p>注：1默认模板不可停用，需先取消默认，再停用</p>
      <p>2默认模板只能设置一个，且必须设置</p>
      <p>
        3可用变量值：{{
          moduleListOptions.data.deviceType == 0 ? '#订单金额#、#通道类型#、#实收金额#' : '#门店名称#、#交易时间#、#订单金额#、#实收金额#、#收银员#'
        }}
      </p>
    </div>
  </a-modal>

  <DeviceModuleForm v-model:open="deviceModuleOptions.open" :formType="deviceModuleOptions.type" :rowData="deviceModuleOptions.data" @ok="onSearch" />
  <DeviceModelForm v-model:open="deviceModelOptions.open" :formType="deviceModelOptions.type" :rowData="deviceModelOptions.data" @ok="onSearch" />
</template>
<script setup>
  import { reactive, ref, onMounted, computed, getCurrentInstance, h } from 'vue'
  import { manufacturerApi } from '/@/api/business/b-operation/manufacturer/index'
  import { deviceModuleApi } from '/@/api/business/b-operation/device-module/index'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const'
  import { smartSentry } from '/@/lib/smart-sentry'
  import { Button, Switch, Modal, message } from 'ant-design-vue'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { selectDictLabel, privilege } from '/@/utils/common'
  import { DEVICE_TYPE, START_STOP } from '/@/constants/dict'
  import DeviceModuleForm from './device-module-form.vue'
  import DeviceModelForm from './device-model-form.vue'
  import DeviceModuleList from './device-module-list.vue'

  const { proxy } = getCurrentInstance()
  // ---------------------------- 表格列 ----------------------------

  const columns = ref([
    {
      title: '序号',
      dataIndex: 'index',
      width: 60,
      customRender: ({ index }) => {
        return (queryForm.pageNo - 1) * queryForm.pageSize + index + 1
      },
    },
    {
      title: '厂商名称',
      dataIndex: 'manufacturerName',
      ellipsis: true,
    },
    {
      title: '设备类型',
      dataIndex: 'deviceType',
      ellipsis: true,
      customRender: (column) => selectDictLabel(DEVICE_TYPE, column.text),
    },
    {
      title: '产品型号',
      dataIndex: 'deviceModelNames',
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'cTime',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      ellipsis: true,
      customRender: ({ record, text }) => {
        return h('div', [
          h(Switch, {
            checked: text,
            checkedValue: 1,
            unCheckedValue: 0,
            onChange: (checked) => {
              changeStatus(checked, record)
            },
          }),
        ])
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      minWidth: 180,
      customRender: ({ record }) => {
        return h('div', [
          // privilege('manufacturer:find_id')
          h(
            Button,
            {
              type: 'link',
              size: 'small',
              onClick: () => {
                showForm(record, 'view')
              },
            },
            '详情',
          ),
          record.status == 0
            ? h(
                Button,
                {
                  type: 'link',
                  size: 'small',
                  onClick: () => {
                    showForm(record, 'update')
                  },
                },
                '修改',
              )
            : '',
          record.status == 0
            ? h(
                Button,
                {
                  type: 'link',
                  size: 'small',
                  onClick: () => {
                    delRow(record)
                  },
                },
                '删除',
              )
            : '',
          record.status == 1
            ? h(
                Button,
                {
                  type: 'link',
                  size: 'small',
                  onClick: () => {
                    showModuleList(record)
                  },
                },
                '设置模板',
              )
            : '',
          record.status == 1
            ? h(
                Button,
                {
                  type: 'link',
                  size: 'small',
                  onClick: () => {
                    showDeviceModel(record)
                  },
                },
                '添加型号',
              )
            : '',
        ])
      },
    },
  ])

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    manufacturerName: undefined,
    manufacturerId: undefined,
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = reactive({ ...queryFormState })
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize
    Object.assign(queryForm, queryFormState)
    queryForm.pageSize = pageSize
    queryData()
  }

  // 搜索
  function onSearch() {
    queryForm.pageNo = 1
    queryData()
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    try {
      let queryResult = await deviceModuleApi.page(queryForm)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  // const getBusinessName = (value) => {
  //   const item = CHANNEL_BUSINESS_TYPE.find((item) => item.value === value)
  //   return item ? item.itemName : null
  // }

  onMounted(() => {
    queryData()
    // getBusinessList()
  })

  // ---------------------------- 添加/修改 ----------------------------
  const deviceModuleOptions = ref({
    open: false,
    data: null,
    type: 'add',
  })

  function showForm(data, type) {
    deviceModuleOptions.value.open = true
    deviceModuleOptions.value.data = data
    deviceModuleOptions.value.type = type
  }
  // 设备型号
  const deviceModelOptions = ref({
    open: false,
    data: null,
    type: 'add',
  })

  function showDeviceModel(data, type) {
    deviceModelOptions.value.open = true
    deviceModelOptions.value.data = data
    deviceModelOptions.value.type = type
  }

  // 设置模板
  const moduleListOptions = ref({
    open: false,
    data: null,
    title: null,
    type: 'add',
  })
  function showModuleList(data, type) {
    moduleListOptions.value.open = true
    moduleListOptions.value.data = data
    moduleListOptions.value.title = `设置模板-${selectDictLabel(DEVICE_TYPE, data.deviceType)}`
    moduleListOptions.value.type = type
  }
  function onmoduleListClose() {
    moduleListOptions.value.open = false
  }

  // 切换状态
  const changeStatus = async (status, row) => {
    Modal.confirm({
      title: '提示',
      content: '确定要修改该状态吗?',
      okText: '确定',
      async onOk() {
        let data = {
          id: row.id,
          status: status,
        }
        deviceModuleApi.updateStatus(data).then((res) => {
          if (res.code == 200) {
            message.success('修改成功')
            queryData()
          } else {
            message.error(res.message)
          }
        })
      },
      cancelText: '取消',
      onCancel() {},
    })
  }

  // ---------------------------- 批量删除 ----------------------------

  // 删除
  async function delRow(record) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除该数据吗?',
      okText: '删除',
      okType: 'danger',
      async onOk() {
        rowDelete(record)
      },
      cancelText: '取消',
      onCancel() {},
    })
  }

  //请求删除
  async function rowDelete(record) {
    try {
      SmartLoading.show()
      await deviceModuleApi.delete({ id: record.id })
      message.success('删除成功')
      queryData()
    } catch (e) {
      console.log(e)
      smartSentry.captureError(e)
    } finally {
      SmartLoading.hide()
    }
  }
</script>

<style lang="less" scoped>
  .notice-alert {
    margin-bottom: 16px;

    :deep(.ant-alert) {
      &.ant-alert-warning {
        background-color: #f59a23;
        border: none;
        padding: 16px 24px;

        .ant-alert-message {
          color: #ffffff;
        }
      }
    }
  }

  .smart-table-btn-block {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    justify-content: space-between;
  }

  .smart-table-title {
    font-size: 16px;
    font-weight: 500;
  }

  .smart-table-operate-block {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .custom-modal {
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1000;
  }

  .modal-content {
    width: 400px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    text-align: center;
  }

  #modal-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .modal-message {
    display: flex;
    align-items: center; /* 垂直居中 */
    margin-bottom: 20px;
  }

  #modal-icon {
    color: #f0ad4e; /* 警告图标的颜色 */
    font-size: 24px;
    margin-right: 10px;
  }

  #modal-content {
    font-size: 14px;
    color: #333;
  }

  .modal-buttons {
    display: flex;
    justify-content: center;
    gap: 10px;
  }

  #modal-ok {
    background-color: #007bff;
    color: #fff;
    border: none;
    padding: 8px 20px;
    border-radius: 4px;
    cursor: pointer;
  }

  #modal-cancel {
    background-color: #f0f0f0;
    color: #333;
    border: 1px solid #ccc;
    padding: 8px 20px;
    border-radius: 4px;
    cursor: pointer;
  }
</style>
